import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/common/charts_pie.dart';
import 'package:enterprise_v6_app/app/data/common/choice_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/application/department_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_summary_binary_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_summary_lesson_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_summary_test_rank_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_summary_three_level_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_summary_top_entity.dart';
import 'package:syncfusion_flutter_gauges/gauges.dart';
// ignore: implementation_imports
import 'package:syncfusion_flutter_gauges/src/radial_gauge/utils/enum.dart' as radial_gauge_utils;

class EducationHomeController extends GetxController {
  @override
  void onInit() {
    super.onInit();
    Future.wait<void>([
      getDepartments(),
      getLessonCount(),
      getLessonFinish(),
      getTeachType(),
      getTeachFinish(),
      getSummary(),
      refreshTimeAndDepartmentRelativeData(),
    ]).then((_) => update());
  }

  String? startDate;
  String? endDate;
  String? get departmentId => selectedDeparment?.getId();

  Map<String, String> lessonTop = {
    '累计学时': '0',
    '课程平均分': '0',
    '全厂排名': '0',
  };

  static const colors = [
    Color(0xFF5C6DFF),
    Color(0xFF1869FF),
    Color(0xFF00D8EF),
    Color(0xFFFD6B6B),
    Color(0xFF14D2B8),
  ];

  final lessonCount = <ChartData>[];

  final lessonFinish = <ChartData>[];

  Map<String, String> planTop = {
    '计划学时': '0',
    '计划时长': '0',
  };

  final teachType = <ChartData>[];

  final teachFinish = <ChartData>[];

  /// 培训：完成 - 未完成
  final teachCount = _BinaryData(
    aVal: 0,
    bVal: 0,
    aName: '已培训人数',
    bName: '未培训人数',
    color: const Color(0xFF5C6DFF),
  );

  /// 课时达标率
  final timePassRate = _BinaryData(
    aVal: 0,
    bVal: 0,
    aName: '已达标人数',
    bName: '未达标人数',
    color: const Color(0xFF5C6DFF),
  );

  /// 考核合格率
  final testPassRate = _BinaryData(
    aVal: 0,
    bVal: 0,
    aName: '已合格人数',
    bName: '未合格人数',
    color: const Color(0xFF14D2B8),
  );

  /// 承包商人员培训
  final contractorTrain = _BinaryData(
    aVal: 0,
    bVal: 0,
    aName: '已培训人数',
    bName: '已通过人数',
    color: const Color(0xFF5C6DFF),
  );

  List<ChoiceBean> departments = [];

  ChoiceBean? selectedDeparment;

  /// 入厂三级培训与承包商培训通过率
  Map<String, int> factoryTrain = {
    '厂级培训': 0,
    '车间工段培训': 0,
    '班组培训': 0,
  };

  final factoryTrainRate = _BinaryData(
    aVal: 0,
    bVal: 0,
    aName: '已培训人数',
    bName: '已通过人数',
    color: const Color(0xFF5C6DFF),
    total: (a, _) => a,
  );

  final testRank = <EducationSummaryTestRankEntity>[];
  final learnTimeRank = <EducationSummaryTestRankEntity>[];

  void showSelect(Function() callback) {
    CustomSelectFunction.selectMultipleBottomSheet<ChoiceBean>(
      onCallBack: (val) {
        selectedDeparment = val.first;
        update();
        callback();
      },
      dataList: departments,
      checkedList: selectedDeparment == null ? [] : [selectedDeparment!],
      isMultiple: false,
    );
  }

  Future<void> getLessonCount() async {
    final resp = await HttpUtil()
        .generateGetRequest<List<EducationSummaryLessonEntity>>(
          '${Interface.mainBaseUrl}/education//getTextbookCount',
        )
        .execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        lessonCount.clear();
        for (final item in data) {
          lessonCount.add(ChartData(item.surveyTypeDicName, item.selectCount, colors[lessonCount.length % colors.length]));
        }
      }
    });
  }

  Future<void> getLessonFinish() async {
    final resp = await HttpUtil()
        .generateGetRequest<EducationSummaryBinaryEntity>(
          '${Interface.mainBaseUrl}/education//getTextbookFinish',
        )
        .execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        lessonFinish.clear();
        lessonFinish.add(ChartData('已完成', data.finishCount, const Color(0xFF1869FF)));
        lessonFinish.add(ChartData('未完成', data.unFinishCount, const Color(0xFFFD6B6B)));
      }
    });
  }

  Future<void> getTeachType() async {
    final resp = await HttpUtil()
        .generateGetRequest<EducationSummaryBinaryEntity>(
          '${Interface.mainBaseUrl}/education//planTypeStatics',
        )
        .execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        teachType.clear();
        teachType.add(ChartData('线上', data.finishCount, const Color(0xFF1869FF)));
        teachType.add(ChartData('线下', data.unFinishCount, const Color(0xFFFD6B6B)));
      }
    });
  }

  Future<void> getTeachFinish() async {
    final resp = await HttpUtil()
        .generateGetRequest<EducationSummaryBinaryEntity>(
          '${Interface.mainBaseUrl}/education//getPlanPlanFinish',
        )
        .execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        teachFinish.clear();
        teachFinish.add(ChartData('已完成', data.finishCount, const Color(0xFF1869FF)));
        teachFinish.add(ChartData('未完成', data.unFinishCount, const Color(0xFFFD6B6B)));
      }
    });
  }

  Future<void> getSummary() async {
    final resp = await HttpUtil()
        .generateGetRequest<EducationSummaryTopEntity>(
          '${Interface.mainBaseUrl}/education//getMyTextbookTop',
        )
        .execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        lessonTop.clear();
        lessonTop['累计学时'] = data.trainingHours.toString();
        lessonTop['课程平均分'] = data.averageScore.toString();
        lessonTop['全厂排名'] = data.ranking.toString();
        planTop.clear();
        planTop['计划学时'] = data.textbookCount.toString();
        planTop['计划时长'] = data.finishHours.toString();
      }
    });
  }

  Future<void> getDepartments() async {
    final resp = await HttpUtil().generateGetRequest<List<DepartmentEntity>>(
      '${Interface.mainBaseUrl}/auth//auth/getBDepartment',
      queryParameters: {'type': '6'},
    ).execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        departments.clear();
        departments.addAll(data);
      }
    });
  }

  /// 承包商
  Future<void> getContractor() async {
    final resp = await HttpUtil().generateGetRequest<EducationSummaryBinaryEntity>(
      '${Interface.mainBaseUrl}/education//getPlanCRate',
      queryParameters: {
        'startDate': startDate,
        'endDate': endDate,
        'departmentId': departmentId,
      },
    ).execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        factoryTrainRate.aVal = data.finishCount;
        factoryTrainRate.bVal = data.unFinishCount;
      }
    });
  }

  Future<void> getCoverRate() async {
    final resp = await HttpUtil().generateGetRequest<EducationSummaryBinaryEntity>(
      '${Interface.mainBaseUrl}/education//getPlanCoverRate',
      queryParameters: {
        'startDate': startDate,
        'endDate': endDate,
        'departmentId': departmentId,
      },
    ).execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        contractorTrain.aVal = data.finishCount;
        contractorTrain.bVal = data.unFinishCount;
      }
    });
  }

  Future<void> getPlanHourRate() async {
    final resp = await HttpUtil().generateGetRequest<EducationSummaryBinaryEntity>(
      '${Interface.mainBaseUrl}/education//getPlanHourRate',
      queryParameters: {
        'startDate': startDate,
        'endDate': endDate,
        'departmentId': departmentId,
      },
    ).execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        timePassRate.aVal = data.finishCount;
        timePassRate.bVal = data.unFinishCount;
      }
    });
  }

  Future<void> getTestPassRate() async {
    final resp = await HttpUtil().generateGetRequest<EducationSummaryBinaryEntity>(
      '${Interface.mainBaseUrl}/education//getPlanKaoRate',
      queryParameters: {
        'startDate': startDate,
        'endDate': endDate,
        'departmentId': departmentId,
      },
    ).execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        testPassRate.aVal = data.finishCount;
        testPassRate.bVal = data.unFinishCount;
      }
    });
  }

  Future<void> getFactoryTrain() async {
    final resp = await HttpUtil().generateGetRequest<EducationSummaryThreeLevelEntity>(
      '${Interface.mainBaseUrl}/education//getPlanThreeRate',
      queryParameters: {
        'startDate': startDate,
        'endDate': endDate,
        'departmentId': departmentId,
      },
    ).execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        factoryTrain['厂级培训'] = data.rate;
        factoryTrain['车间工段培训'] = data.carRate;
        factoryTrain['班组培训'] = data.classRate;
      }
    });
  }

  Future<void> getTestRank() async {
    final resp = await HttpUtil().generateGetRequest<List<EducationSummaryTestRankEntity>>(
      '${Interface.mainBaseUrl}/education//listKaoRank',
      queryParameters: {
        'startDate': startDate,
        'endDate': endDate,
        'departmentId': departmentId,
      },
    ).execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        testRank.clear();
        testRank.addAll(data);
      }
    });
  }

  Future<void> getLearnTimeRank() async {
    final resp = await HttpUtil().generateGetRequest<List<EducationSummaryTestRankEntity>>(
      '${Interface.mainBaseUrl}/education//listHoursRank',
      queryParameters: {
        'startDate': startDate,
        'endDate': endDate,
        'departmentId': departmentId,
      },
    ).execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        learnTimeRank.clear();
        learnTimeRank.addAll(data);
      }
    });
  }

  Future<void> refreshTimeAndDepartmentRelativeData() async {
    await Future.wait([
      getContractor(),
      getCoverRate(),
      getPlanHourRate(),
      getTestPassRate(),
      getFactoryTrain(),
      getTestRank(),
      getLearnTimeRank(),
    ]);
    update();
  }
}

/// 有两种可能的数据
class _BinaryData {
  _BinaryData({
    required this.aVal,
    required this.bVal,
    required this.aName,
    required this.bName,
    required this.color,
    this.total,
  });

  int aVal;
  int bVal;
  final String aName;
  final String bName;
  final Color color;
  final int Function(int a, int b)? total;

  Widget get build {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        _buildCircleProgress(
          value: aVal,
          total: total?.call(aVal, bVal) ?? bVal + aVal,
        ),
        Column(
          children: [
            Row(
              children: [
                Text(
                  aName,
                  style: TextStyle(
                    fontSize: 13.w,
                    color: const Color(0xFF959595),
                  ),
                ),
                AppGaps.hGap10,
                Text(
                  '$aVal',
                  style: TextStyle(color: color, fontWeight: FontWeight.w400, fontSize: 16.sp),
                ),
              ],
            ),
            Row(
              children: [
                Text(
                  bName,
                  style: TextStyle(
                    fontSize: 13.w,
                    color: const Color(0xFF959595),
                  ),
                ),
                AppGaps.hGap10,
                Text(
                  '$bVal',
                  style: TextStyle(color: color, fontWeight: FontWeight.w400, fontSize: 16.sp),
                ),
              ],
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildCircleProgress({
    required int value,
    required int total,
  }) {
    return SizedBox(
      height: 90.w,
      width: 90.w,
      child: SfRadialGauge(
        axes: <RadialAxis>[
          RadialAxis(
            radiusFactor: 0.85,
            axisLineStyle: AxisLineStyle(color: const Color(0xFFE0E4EB).withOpacity(0.8), thickness: 0.24, thicknessUnit: GaugeSizeUnit.factor),
            showLabels: false,
            showTicks: false,
            startAngle: 270,
            endAngle: 270,
            pointers: <GaugePointer>[
              RangePointer(
                pointerOffset: 0.05,
                width: 0.15,
                value: value != 0 ? (value / total) * 100 : 0,
                cornerStyle: radial_gauge_utils.CornerStyle.bothCurve,
                color: color,
                sizeUnit: GaugeSizeUnit.factor,
              ),
            ],
            annotations: <GaugeAnnotation>[
              GaugeAnnotation(
                widget: Text(
                  value != 0 && total != 0 ? '${((value / total) * 100).toInt()}%' : '0%',
                  style: TextStyle(color: color, fontWeight: FontWeight.w400, fontSize: 16.sp),
                ),
                positionFactor: 0.15,
                angle: 90,
              )
            ],
          )
        ],
      ),
    );
  }
}
